package com.mad.trafficclient.util;

import android.content.Context;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class NetUtil {
    private String url;
    private UrlBean urlBean;

    public NetUtil(Context context) {
        this.urlBean = Util.loadSetting(context);
        url = "http://" + urlBean.getUrl() + ":" + urlBean.getPort() + "/transportservice/type/jason/action/";
    }

    //异步请求
    public void async(String json, String action, final OnRequestResult onRequestResult) {
        //body
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        RequestBody body = RequestBody.create(mediaType, json);

        //请求主体
        Request request = new Request.Builder()
                .url(url + action)
                .post(body)
                .build();

        OkHttpClient client = new OkHttpClient();
        //client.newCall(request).execute().body().string();同步请求
        client.newCall(request).enqueue(new Callback() {   //异步请求
            @Override
            public void onFailure(Call call, IOException e) {
                onRequestResult.onFailure(e);
                LoadingDialog.disDialog();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string();

                try {
                    //解析serverinfo
                    JSONObject jsonObject = new JSONObject(result);
                    String serverinfo = jsonObject.getString("serverinfo");
                    onRequestResult.onResponse(serverinfo);
                } catch (JSONException e) {
                    onRequestResult.onFailure(e);
                    e.printStackTrace();
                }
            }
        });
    }

    public interface OnRequestResult {
        void onFailure(Exception e);

        void onResponse(String result);
    }
}
